package com.sanhuo.idms.controller;


import com.sanhuo.file.service.FileService;
import com.sanhuo.idms.bo.AdminUpdateStudentBO;
import com.sanhuo.idms.bo.StudentPageBO;
import com.sanhuo.idms.entity.Clas;
import com.sanhuo.idms.entity.Dorm;
import com.sanhuo.idms.entity.Student;
import com.sanhuo.idms.service.ClasService;
import com.sanhuo.idms.service.DormService;
import com.sanhuo.idms.service.StudentService;
import com.sanhuo.idms.vo.StudentDetailVO;
import com.sanhuo.idms.vo.StudentPageVO;
import com.sanhuo.idms.vo.StudentVO;
import com.sanhuo.lib.ExceptionUtil;
import com.sanhuo.lib.exception.GlobalException;
import com.sanhuo.security.bo.UserUpdateBO;
import com.sanhuo.security.entity.User;
import com.sanhuo.security.service.UserService;
import com.sanhuo.security.uitls.UserHolder;
import com.sanhuo.triild.page.Page;
import com.sanhuo.triild.page.PageSearch;
import com.sanhuo.utils.basic.BeanUtil;
import com.sanhuo.utils.office.OfficeUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("student")
@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;
    @Autowired
    private FileService fileService;
    @Autowired
    private DormService dormService;
    @Autowired
    private ClasService clasService;

    @RequestMapping("")
    public List<StudentPageVO> findAll(StudentPageBO pageBO) throws IllegalAccessException {
        List<Student> studentList = studentService.findAll(pageBO);
        return studentService.addDromAndCollegeData(studentList);
    }

    @Transactional
    @RequestMapping("excal/save")
    public void saveFromExcal(MultipartFile file) throws IOException {
        ExceptionUtil.throwException(BeanUtil.isNull(file), "上传文件不能为空");
        Workbook workbook = OfficeUtil.readFile(file);
        Sheet sheet = workbook.getSheetAt(0);
        Cell isThis = sheet.getRow(0).getCell(0);
        if (!"新增学生模板表".equals(isThis.getStringCellValue())) {
            throw new GlobalException("请上传正确的文件");
        }
        Row title = sheet.getRow(2);
        for (int rowNum = 3; rowNum <= sheet.getLastRowNum(); rowNum++) {
            Row row = sheet.getRow(rowNum);
            if (row != null) {
                int cellNum = row.getLastCellNum();
                for (int num = 0; num < cellNum; num++) {
                    Cell cell = row.getCell(num);
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                    }
                }
                Student student = new Student();
                User user = new User();
                String id = row.getCell(0).getStringCellValue();
                student.setId(id);
                user.setId(id);
                String name = row.getCell(1).getStringCellValue();
                student.setName(name);
                user.setName(name);
                String gender = row.getCell(2).getStringCellValue();
                student.setGender(gender);
                String dorm = row.getCell(3).getStringCellValue();
                Integer dormNum = new Integer(dorm.substring(0, dorm.lastIndexOf("-")));
                Integer tungNum = new Integer(dorm.substring(dorm.lastIndexOf("-") + 1));
                Dorm d = dormService.findByNum(dormNum, tungNum);
                if (!BeanUtil.isNull(d)) {
                    student.setDormId(d.getId());
                }
                String clas = row.getCell(4).getStringCellValue();
                String clasGrade = clas.substring(0, 2);
                String collegeId = clas.substring(2, 4);
                String clasNum = clas.substring(4);
                Clas c = clasService.findByNum(collegeId, clasGrade, clasNum);
                if (!BeanUtil.isNull(c)) {
                    student.setClasId(c.getId());
                }
                if (row.getCell(5) != null) {
                    String phone = row.getCell(5).getStringCellValue();
                    user.setPhone(phone);
                }
                if (row.getCell(6) != null) {
                    String qq = row.getCell(6).getStringCellValue();
                    user.setQq(qq);
                }
                if (row.getCell(7) != null) {
                    String email = row.getCell(7).getStringCellValue();
                    user.setEmail(email);
                }
                user.setPassword("12345678");
                user.setRoleId("03");
                user.creatorAndUpdatorInfo(UserHolder.user());
                student.creatorAndUpdatorInfo(UserHolder.user());
                userService.save(user);
                studentService.save(student);
            }
        }
    }

    @RequestMapping("excal")
    public void getExcal(HttpServletRequest req, HttpServletResponse res) throws ParseException, IOException {
        String path = "C:\\student.xlsx";//路径
        XSSFWorkbook workbook = new XSSFWorkbook();
        //新建工作表,sheetName为工作表名称
        XSSFSheet sheet = workbook.createSheet("新增学生模板");
        XSSFCellStyle titleStyle = workbook.createCellStyle();  //创建行
        titleStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION); // 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);   //垂直居中
        XSSFRow row0 = sheet.createRow(0);   //第一行,row为行
        //创建单元格行号由row确定,列号作为参数传递给createCell;第一列从0开始计算
        XSSFCell cell0 = row0.createCell(0);//cell为格,第一格
        //给单元格赋值,设置excal表格第一行
        cell0.setCellValue("新增学生模板表");
        //将第一行的前10个单元格合并
        CellRangeAddress cra = new CellRangeAddress(0, 1, 0, 10);
        sheet.addMergedRegion(cra);
        cell0.setCellStyle(titleStyle);//设置样式
        XSSFRow row = sheet.createRow(2);
        //设置第二行
        List<String> title = new ArrayList<>();
        title.add("学号");
        title.add("姓名");
        title.add("性别");
        title.add("宿舍(楼层-宿舍号)");
        title.add("班级");
        title.add("手机号(可不填)");
        title.add("QQ(可不填)");
        title.add("邮箱(可不填)");
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        for (int i = 0; i < title.size(); i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(title.get(i));
            cell.setCellStyle(cellStyle);
            sheet.setColumnWidth(i, 25 * 256);
        }
        //创建输出流,将生成的excal文件保存到本地
        FileOutputStream fos = new FileOutputStream(new File(path));
        workbook.write(fos);
        workbook.close();
        fos.close();
        fileService.downloadLocalFile(path, "新增学生模板.xlsx", req, res);
    }


    @RequestMapping("list")
    public Page<StudentPageVO> listAll(StudentPageBO pageBO, PageSearch pageSearch) {
        pageSearch.setOrderBy(" s.updateTime desc ");
        return studentService.listAll(pageBO, pageSearch);
    }

    @RequestMapping("detail")
    public StudentDetailVO detail(String id) throws IllegalAccessException {
        return studentService.addDetailData(id);
    }

    @RequestMapping("findOne")
    public StudentVO findById(String id) {
        StudentVO vo = studentService.detail(id);
        return studentService.detail(id);
    }


    @RequestMapping("update/admin")
    public void update(AdminUpdateStudentBO bo) throws IllegalAccessException {
        studentService.adminUpdateStudent(UserHolder.user(), bo);
    }

    @RequestMapping("update")
    public void update(UserUpdateBO bo) {
        userService.update(bo);
    }

    @RequestMapping("dorm")
    public List<Student> findByDormId(String dormId) {
        return studentService.findByDormId(dormId);
    }


}
